package tecpizza;

import java.sql.ResultSet;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import negocio.Tamanho;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author tecnico
 */
public class TelaTamanhos extends javax.swing.JFrame {

    /**
     * Creates new form Tamanhos
     */
    public TelaTamanhos() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1Nome = new javax.swing.JLabel();
        jLabel2Preco = new javax.swing.JLabel();
        jTextNome = new javax.swing.JTextField();
        jTextPreco = new javax.swing.JTextField();
        jButtonSalvar = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jButtonAlterar = new javax.swing.JButton();
        jTextCodigo = new javax.swing.JTextField();
        jLabelAtivo = new javax.swing.JLabel();
        jCheckAtivo = new javax.swing.JCheckBox();

        setTitle("Tec-Pizza");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

        jLabel1Nome.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jLabel1Nome.setText("Nome :");

        jLabel2Preco.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jLabel2Preco.setText("Preço :");

        jButtonSalvar.setText("Salvar");
        jButtonSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSalvarActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Arial Black", 1, 14)); // NOI18N
        jLabel3.setText("Cadastro de Tamanhos");

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Código", "Nome", "Preço", "Ativo", "Alterar", "Excluir"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.Float.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, true, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable2MouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(jTable2);
        jTable2.getColumnModel().getColumn(0).setResizable(false);
        jTable2.getColumnModel().getColumn(1).setResizable(false);
        jTable2.getColumnModel().getColumn(2).setResizable(false);
        jTable2.getColumnModel().getColumn(3).setResizable(false);
        jTable2.getColumnModel().getColumn(4).setResizable(false);
        jTable2.getColumnModel().getColumn(5).setResizable(false);

        jButtonAlterar.setText("Alterar");
        jButtonAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAlterarActionPerformed(evt);
            }
        });

        jTextCodigo.setEditable(false);

        jLabelAtivo.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jLabelAtivo.setText("Ativo :");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 10, Short.MAX_VALUE)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(126, 126, 126)
                                .addComponent(jLabel3))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(46, 46, 46)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel1Nome)
                                        .addGap(18, 18, 18)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(jTextNome, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addComponent(jTextCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel2Preco)
                                        .addGap(18, 18, 18)
                                        .addComponent(jTextPreco, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabelAtivo)
                                        .addGap(18, 18, 18)
                                        .addComponent(jCheckAtivo))))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(146, 146, 146)
                                .addComponent(jButtonAlterar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jButtonSalvar)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(36, 36, 36)
                .addComponent(jLabel3)
                .addGap(29, 29, 29)
                .addComponent(jTextCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1Nome)
                    .addComponent(jTextNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2Preco)
                    .addComponent(jTextPreco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelAtivo)
                    .addComponent(jCheckAtivo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 14, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonSalvar)
                    .addComponent(jButtonAlterar))
                .addGap(35, 35, 35)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(27, 27, 27))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSalvarActionPerformed

        
        if(jTextNome.getText().equals("")){
            JOptionPane.showMessageDialog(null,"Erro ! O campo nome nao foi preenchido");
            return;
        }
        if(jTextPreco.getText().equals("")){
            JOptionPane.showMessageDialog(null, "Erro ! O campo preço não foi preenchido"); 
            return;
        }
        
        Tamanho tamanho = new Tamanho();
        tamanho.setNome(jTextNome.getText());
        tamanho.setPreco(Float.parseFloat(jTextPreco.getText()));
        if (!jTextCodigo.getText().equals("")){
            tamanho.setCodigo(Integer.parseInt(jTextCodigo.getText()));
        }
        tamanho.salvar();
        
        JOptionPane.showMessageDialog(null, "Tamanho foi cadastrado com Sucesso!");
        jTextNome.setText("");
        jTextPreco.setText("");
    }//GEN-LAST:event_jButtonSalvarActionPerformed

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
        // TODO add your handling code here:
        jButtonAlterar.setVisible(false);
        jButtonSalvar.setVisible(true);
        jTextCodigo.setVisible(false);
        jLabelAtivo.setVisible(false);
        jCheckAtivo.setVisible(false);
        atualizaTabela();
    }//GEN-LAST:event_formWindowActivated

    private void jTable2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable2MouseClicked
        // TODO add your handling code here:
       Tamanho tamanho = new Tamanho();
        if (jTable2.getModel().getValueAt(jTable2.getSelectedRow() ,4)==true){
            jTextNome.setText(jTable2.getModel().getValueAt(jTable2.getSelectedRow() ,1).toString());
            jTextPreco.setText(jTable2.getModel().getValueAt(jTable2.getSelectedRow() ,2).toString());
            jTextCodigo.setText(jTable2.getModel().getValueAt(jTable2.getSelectedRow() ,0).toString());
            jCheckAtivo.setSelected(Boolean.parseBoolean(jTable2.getModel().getValueAt(jTable2.getSelectedRow() ,3).toString()));
            jButtonAlterar.setVisible(true);
            jButtonSalvar.setVisible(false);
            jLabelAtivo.setVisible(true);
            jCheckAtivo.setVisible(true);
            jTable2.getModel().setValueAt(false, jTable2.getSelectedRow() ,4);
        }else if (jTable2.getModel().getValueAt(jTable2.getSelectedRow() ,5)==true){
            if (JOptionPane.showConfirmDialog(null,"Deseja excluir o tamanho " + 
                    jTable2.getModel().getValueAt(jTable2.getSelectedRow() ,1).toString() + " ?",
                    "Confirma Exclusão",JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION){
               if (tamanho.podeExcluir(Integer.parseInt(jTable2.getModel().getValueAt(jTable2.getSelectedRow() ,0).toString()))){
                    tamanho.excluir(Integer.parseInt(jTable2.getModel().getValueAt(jTable2.getSelectedRow() ,0).toString()));
                    JOptionPane.showMessageDialog(null,"Registro excluído com sucesso.");
               }else{
                   JOptionPane.showMessageDialog(null,"Este registro não pode ser excluído pois já foi utilizado em pedidos.");
               }
            }
        }
    }//GEN-LAST:event_jTable2MouseClicked

    private void jButtonAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAlterarActionPerformed
        if(jTextNome.getText().equals("")){
            JOptionPane.showMessageDialog(null,"Erro ! O campo nome não foi preenchido");
            return;
        }
        if(jTextPreco.getText().equals("")){
            JOptionPane.showMessageDialog(null, "Erro ! O campo preço não foi preenchido"); 
            return;
        }
        
        Tamanho tamanho = new Tamanho();
        tamanho.setNome(jTextNome.getText());
        tamanho.setPreco(Float.parseFloat(jTextPreco.getText()));
        tamanho.setCodigo(Integer.parseInt(jTextCodigo.getText()));
        tamanho.setAtivo(jCheckAtivo.isSelected());
        tamanho.alterar();
        
        JOptionPane.showMessageDialog(null, "Tamanho alterado com Sucesso!");
        jTextNome.setText("");
        jTextPreco.setText("");
        jCheckAtivo.setSelected(false);
    }//GEN-LAST:event_jButtonAlterarActionPerformed

    private void atualizaTabela(){
        DefaultTableModel tTabela = (DefaultTableModel) jTable2.getModel();
        tTabela.setNumRows(0);
        Tamanho tam = new Tamanho();
        
        List<Tamanho> tamanhos = tam.getAll();
        if (tamanhos!=null){
            for (int linha = 0; linha < tamanhos.size(); linha++)
            {
                Tamanho tamanho = tamanhos.get(linha);

                tTabela.addRow(new Object[]{1});

                jTable2.setValueAt(tamanho.getCodigo(), linha, 0);
                jTable2.setValueAt(tamanho.getNome(), linha, 1);
                jTable2.setValueAt(tamanho.getPreco(), linha, 2);
                jTable2.setValueAt(tamanho.isAtivo(), linha, 3);
            }
        }
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TelaTamanhos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TelaTamanhos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TelaTamanhos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TelaTamanhos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new TelaTamanhos().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAlterar;
    private javax.swing.JButton jButtonSalvar;
    private javax.swing.JCheckBox jCheckAtivo;
    private javax.swing.JLabel jLabel1Nome;
    private javax.swing.JLabel jLabel2Preco;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabelAtivo;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable2;
    private javax.swing.JTextField jTextCodigo;
    private javax.swing.JTextField jTextNome;
    private javax.swing.JTextField jTextPreco;
    // End of variables declaration//GEN-END:variables
}
